<template>
	<div class="container-fluid">
		<div class="panel">
			<div class="panel-heading">
				<el-row :gutter="20">
					<el-col :span="18">
						<div class="grid-content bg-purple">
							<h3 class="panel-title">通知列表</h3>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="grid-content bg-purple">
							<el-button type="primary" icon="el-icon-plus" class="pull-right" plain @click="createPost">通知</el-button>
							<!-- 创建 -->
							<el-dialog title="发布通知" :visible.sync="create" width="35%" @close="handleCreateFormClose">
								<el-form :model="createParams" :rules="createRules" ref="createNotificationForm">
									<el-form-item prop="title" label="标题">
										<el-input v-model="createParams.title"></el-input>
									</el-form-item>
									<el-form-item prop="content" label="内容">
										<el-input type="textarea" v-model="createParams.content"></el-input>
									</el-form-item>
									<el-upload
									  class="upload-demo"
									  action="/api/Upload"
									  :before-remove="beforeRemove"
									  :on-success="fileSuccess"
									  :headers="myHeaders"
									  :limit="1"
									  :before-upload="uploadQian"
									  :on-exceed="handleExceed"
									  :file-list="fileList">
									  <el-button size="small" type="primary" icon="el-icon-upload">上传</el-button>
									  <div slot="tip" class="el-upload__tip">不超过10MB</div>
									</el-upload>
								</el-form>
								<div slot="footer" class="dialog-footer">
									<el-button @click="create = false">取 消</el-button>
									<el-button type="primary" @click="submitCreateForm">确 定</el-button>
								</div>
							</el-dialog>
							<!-- 修改 -->
							<el-dialog title="修改通知" :visible.sync="update" width="35%" @close="handleUpdateFormClose">
								<el-form :model="editParams" :rules="editRules" ref="editNotificationForm">
									<el-form-item prop="title" label="标题">
										<el-input v-model="editParams.title"></el-input>
									</el-form-item>
									<el-form-item prop="content" label="内容">
										<el-input type="textarea" v-model="editParams.content"></el-input>
									</el-form-item>
									<el-upload
									  class="upload-demo"
									  action="/api/Upload"
									  :before-remove="beforeRemove_edit"
									  :on-success="fileSuccess_edit"
									  :headers="myHeaders"
									  :limit="1"
									  :before-upload="uploadQian"
									  :on-exceed="handleExceed_edit"
									  :file-list="fileList_edit">
									  <el-button size="small" type="primary" icon="el-icon-upload">上传</el-button>
									  <div slot="tip" class="el-upload__tip">不超过10MB</div>
									</el-upload>
								</el-form>
								<div slot="footer" class="dialog-footer">
									<el-button @click="update = false">取 消</el-button>
									<el-button type="primary" @click="submitUpdateForm">确 定</el-button>
								</div>
							</el-dialog>
						</div>
					</el-col>
				</el-row>
			</div>
			<div class="panel-body">
				<el-table :data="notifications.data" style="width: 100%" v-loading="loading">
					<el-table-column label="标题">
						<template slot-scope="scope">
							<span v-html="JSON.parse(scope.row.data).title"></span>
						</template>
					</el-table-column>
					<el-table-column label="内容">
						<template slot-scope="scope">
							<span v-html="JSON.parse(scope.row.data).content"></span>
						</template>
					</el-table-column>
					<el-table-column label="附件">
						<template slot-scope="scope">
							<el-button size="mini" v-if="JSON.parse(scope.row.data).path"  type="default" icon="el-icon-download" @click="download(JSON.parse(scope.row.data).path)" plain></el-button>
						</template>
					</el-table-column>
					<el-table-column label="创建时间" prop="created_at"></el-table-column>
					<el-table-column label="操作">
						<template slot-scope="scope">
							<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
							<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" plain>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div class="panel-footer text-right">
				<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
											 :current-page="current"
											 :page-sizes="[10, 20, 50, 100]"
											 :page-size="queryParams.paginate"
											 layout="total, sizes, prev, pager, next, jumper"
											 :total="notifications.total">
				</el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
	import Vue from 'vue'
	import api from '../apis'
	import store from '../store'
	import notification from "../apis/modules/notification";

	export default {
		name: "notification",
		data () {
			return {
				fileList:[],
				fileList_edit:[],
				myHeaders: {Authorization: `Bearer ${store.state.account.access_token}`},
				url: '/notification/',
				loading: false,
				current: 1,
				create: false,
				update: false,
				notifications: {
					data: [],
					total: 0,
				},
				id: null,
				index: null,
				editorOption: {},
				createParams: {
					title: '',
					content: '',
					path: ''
				},
				editParams: {
					title: '',
					content: '',
					path: ''
				},
				queryParams: {
					page: 1,
					paginate: 10,
					data: '',
				},
				createRules: {
					title: [
						{ required: true, message: '请输入通知标题', trigger: 'blur' }
					],
					content: [
						{ required: true, message: '请输入通知内容', trigger: 'blur' }
					]
				},
				editRules: {
					title: [
						{ required: true, message: '请输入通知标题', trigger: 'blur' }
					],
					content: [
						{ required: true, message: '请输入通知内容', trigger: 'blur' }
					]
				}
			}
		},
		methods: {
			/**
			 * 上传文件之前
			 */
			uploadQian(file){
				if(file.size > 20971520){
					this.$message({
						duration: 6000,
						message: '文件上传内容不能查过10MB,当前上传文件'+Math.ceil(file.size/1024/1024)+'MB',
						type: 'warning'
					});
					return false;
				}
			},
			/**
			 * 点击下载
			 */
			download(url){
				window.location.href = url;
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			/**
			 * 删除确认
			 */
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`)
				.then(() => {
		          this.$message({
		            type: 'success',
		            message: '删除成功!'
		          });
		          this.createParams.path = ''
		        }).catch(() => {

		          this.$message({
		            type: 'info',
		            message: '已取消删除'
		          });

		        });

			},
			fileSuccess(response, file, fileList){
				this.createParams.path = file.response.url
			},
			handleExceed_edit(files, fileList) {
				this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			beforeRemove_edit(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
				// .then(() => {
		  //         this.$message({
		  //           type: 'success',
		  //           message: '删除成功!'
		  //         });
		  //         this.editParams.path = ''
		  //       }).catch(() => {

		  //         this.$message({
		  //           type: 'info',
		  //           message: '已取消删除'
		  //         });

		  //       });

			},
			fileSuccess_edit(response, file, fileList){
				this.editParams.path = file.response.url
			},
			/**
			 * 获取通知数据集合
			 */
			fetchNotifications () {
				this.loading = true;
				api.notification.fetch(this.queryParams).then(response => {
					this.notifications = response.data;
					this.loading = false;
				});
			},
			/**
			 * 当改变分页大小时触发
			 */
			handleSizeChange (paginate) {
				this.queryParams.paginate = paginate;
				this.fetchNotifications();
			},
			/**
			 * 当改变页码时触发
			 */
			handleCurrentChange (page) {
				this.queryParams.page = page;
				this.fetchNotifications();
			},
			createPost () {
				this.create = true;
			},
			/**
			 * 创建提交
			 */
			submitCreateForm () {
				this.$refs['createNotificationForm'].validate((valid) => {
					if (valid) {
						api.notification.store(this.createParams).then(response => {
							this.create = false;
							this.$message.success('创建成功');
							this.notifications.total += 1;
							this.notifications.data.unshift(response.data);
							this.fetchNotifications();
						});
					} else {
						return false;
					}
				});
			},
			/**
			 * 关闭创建表单是触发
			 */
			handleCreateFormClose () {
				this.create = false;
				this.$refs['createNotificationForm'].resetFields();
			},
			/**
			 * 点击编辑按钮时触发
			 */
			handleEdit (index, row) {
				console.log(row.data)
				let data = JSON.parse(row.data);
				this.update = true;
				this.editParams = {...data};
				this.id = row.id;

				this.fileList_edit = [];

				if(data.path != '' && data.path != null){
					var fileList = {
						name: this.fileWenJianMing(data.path), 
						url: data.path
					};
					this.fileList_edit.push(fileList);
					console.log(this.fileList_edit)
					this.index = index;
				}
				
			},
			/**
			 * 获取文件名称
			 */
			fileWenJianMing (str){
				if(str != "" && str != undefined && str != 'null')
				return str.substring(str.lastIndexOf("/") + 1)
			},
			/**
			 * 修改提交
			 */
			submitUpdateForm () {
				this.$refs['editNotificationForm'].validate((valid) => {
					if (valid) {
						api.notification.update(this.id, this.editParams).then(response => {
							this.update = false;
							this.$message.success('修改成功');
							Vue.set(this.notifications.data, this.index, response.data);
							this.id = null;
							this.index = null;
							this.fetchNotifications();
						});
					} else {
						return false;
					}
				});
			},
			handleUpdateFormClose () {
				this.update = false;
				this.$refs['editNotificationForm'].resetFields();
			},
			/**
			 * 删除
			 */
			handleDelete (index, row) {
				this.$confirm('此操作将删除Banner信息, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					api.notification.destroy(row.id).then(() => {
						//遍历分类集合删除指定的ID的分类
						Vue.delete(this.notifications.data, index);
						this.$message.success('删除成功');
						this.fetchNotifications();
					}).catch(errors => {
						this.$message.error(errors.response.data.error);
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			}
		},
		mounted () {
			this.fetchNotifications();
		}
	}
</script>

<style>

</style>
